﻿using Hangfire;
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyInjection;
using NewRetail.Application.Components.Platform;
using NewRetail.Application.Components.WeChat.Services.BackgroundServices;
using System;

namespace NewRetail.Application.Worker
{
    public static class WorkerExtension
    {
        public static void StartWorkers(this IApplicationBuilder app)
        {
            using var s = app.ApplicationServices.CreateScope();
            var recurringJobManager = s.ServiceProvider.GetRequiredService<IRecurringJobManager>();
            var backgroundJobClient = s.ServiceProvider.GetRequiredService<IBackgroundJobClient>();

            recurringJobManager.AddOrUpdate<PosDaySumWorker>(nameof(PosDaySumWorker),
                x => x.Trigger(),
                Cron.Hourly(minute: 1),
                timeZone: TimeZoneInfo.Utc);
            #region add by cl
            //每分钟刷新下微信AccessToken
            recurringJobManager.AddOrUpdate<WeChatAccessTokenRefreshingWorker>(nameof(WeChatAccessTokenRefreshingWorker),
                x => x.Execute(),
                Cron.Minutely(),
                timeZone: TimeZoneInfo.Utc);
            //每天刷新下微信商户平台证书
            recurringJobManager.AddOrUpdate<WxpayCertificateRefreshingWorker>(nameof(WxpayCertificateRefreshingWorker),
                x => x.Execute(),
                Cron.Daily(),
                timeZone: TimeZoneInfo.Utc);
            //定时刷新dashboard推送的数据
            recurringJobManager.AddOrUpdate<DashboardRefreshingWorker>(nameof(DashboardRefreshingWorker),
                x => x.Execute(),
                Cron.Minutely(),
                timeZone: TimeZoneInfo.Utc);
            //每天刷新下用户券的状态
            recurringJobManager.AddOrUpdate<MemberCardVoucherRefreshingWorker>(nameof(MemberCardVoucherRefreshingWorker),
                x => x.Execute(),
                Cron.Daily(),
                timeZone: TimeZoneInfo.Utc);
            //每分钟同步下微信微信会员积分
            recurringJobManager.AddOrUpdate<MemberIntegralSyncWechatWorker>(nameof(MemberIntegralSyncWechatWorker),
                x => x.Execute(),
                Cron.Minutely(),
                timeZone: TimeZoneInfo.Utc);
            #endregion
            backgroundJobClient.Schedule<EnsureDatabaseCreatedWoker>(x => x.Execute(),
                delay: TimeSpan.FromSeconds(10));

            backgroundJobClient.Schedule<INoGeneratorService>(
                x => x.GenerateNoWithDistributedLockAsync("application-started"),
                delay: TimeSpan.FromSeconds(3));
        }
    }
}
